package me.hekr.iotos.api.dto;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonTypeName;
import me.hekr.iotos.api.enums.CheckType;
import me.hekr.iotos.api.enums.DataType;

@JsonTypeName("RANGE")
@JsonInclude(Include.NON_NULL)
public class DataValueRangeChecker implements DataValueChecker {
  private ModelParamValue<? extends Number> max;
  private ModelParamValue<? extends Number> min;

  @Override
  public CheckType getType() {
    return CheckType.RANGE;
  }

  @Override
  public boolean isValid(DataType dataType, Object value) {
    if (!DataType.isValid(dataType, value)) {
      return false;
    } else {
      DataType datatype = DataType.fromValue(value);
      boolean isTypeValid = datatype == DataType.INT || datatype == DataType.FLOAT;
      if (!isTypeValid) {
        return false;
      } else {
        double dVal = ((Number) value).doubleValue();
        return dVal >= ((Number) this.min.getValue()).doubleValue()
            && dVal <= ((Number) this.max.getValue()).doubleValue();
      }
    }
  }

  @Override
  public boolean canConvertTo(DataType dataType) {
    return true;
  }

  @Override
  public boolean valid(DataType dataType) {
    return this.max != null
        && this.min != null
        && this.max.getValue() != null
        && this.min.getValue() != null;
  }
}
